package com.example.system.security.controller;

import com.example.common.exception.CustomException;
import com.example.system.security.dto.LoginRequest;
import com.example.system.security.service.AuthService;
import com.example.system.security.service.CaptchaService;
import com.example.system.security.util.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.data.redis.core.StringRedisTemplate;


import java.util.Map;

@RestController
@RequestMapping("/auth")
public class AuthController {
    
    @Autowired
    private StringRedisTemplate redisTemplate;
    
    @Autowired
    private CaptchaService captchaService;
    
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    
    @Autowired
    private AuthService authService;
    
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody LoginRequest request) {
        try {
            captchaService.validateCaptcha(request.getUuid(), request.getCaptcha());
            
            Map<String, Object> loginResult = authService.login(request.getUsername(), request.getPassword());
            
            return ResponseEntity.ok(loginResult);
        } catch (CustomException e) {
            // 验证码
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        } catch (BadCredentialsException e) {
            // 用户名或密码错误
            return ResponseEntity.status(401).body(Map.of("error", "用户名或密码错误"));
        } catch (Exception e) {
            // 其他异常
            return ResponseEntity.status(500).body(Map.of("error", "服务器内部错误"));
        }
    }
    
    @PostMapping("/logout")
    public ResponseEntity<?> logout(@RequestHeader("Authorization") String authHeader) {
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return ResponseEntity.badRequest().body("无效的Token");
        }
        
        String token = authHeader.substring(7);
        if (!jwtTokenUtil.validateToken(token)) {
            return ResponseEntity.badRequest().body("Token验证失败");
        }
        
        String username = jwtTokenUtil.getUsernameFromToken(token);
        String key = "login:token:" + username;
        
        redisTemplate.delete(key);
        return ResponseEntity.ok(Map.of("message", "退出登录成功"));
    }
}
